//
//  YWSettingsViewController.m
//  maintain
//
//  Created by Kyo on 15/11/3.
//  Copyright © 2015年 ewin. All rights reserved.
//


#import "YWSettingsViewController.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "WMHttpTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"
#import "YWLoginTool.h"
#import "DJWActionSheet.h"

#import "YWNewMessageSettingViewController.h"
#import "YWFunctionSettingTableViewController.h"
#import "YWDownloadMetaDataManager.h"
#import "YWErrorRecordFunctionViewController.h"
#import "YWAboutEwinViewController.h"
#import "YWOrganization.h"
#import "YWPopupOrganizationViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "YWEwinManager.h"
#import "YWWorkReminderManager.h"

static NSString *const KLastRefreshJsonDataUserDefaultsKey = @"KLastRefreshJsonDataUserDefaultsKey";

@interface YWSettingsViewController () <UITableViewDelegate, UITableViewDataSource,YWPopupSelectOrganizationDelegate>{
    YWLoginUser *currentUser;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray* titleArray;

@property (nonatomic, strong) YWPopupOrganizationViewController* popupOrganizationViewController;
@property (nonatomic, strong) UISwitch *netWorkSwitch;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWSettingsViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"settings", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    currentUser = [YWLoginTool loginUser];

    self.tableView.backgroundColor = [UIColor customBackgroudColor];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (MBProgressHUD*)HUD{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextLogouting, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (NSArray*)titleArray{
    if (!_titleArray) {
        NSString *changeOrganization = NSLocalizedString(@"changeOrganization", nil);
        NSString *networkDataUse = NSLocalizedString(@"networkDataUse", nil);
        NSString *updateData = NSLocalizedString(@"updateData", nil);
        NSString *function = NSLocalizedString(@"function", nil);
        NSString *errorDiagnosis = NSLocalizedString(@"errorDiagnosis", nil);
        NSString *newMessage = NSLocalizedString(@"newMessage", nil);
        NSString *aboutEwin = NSLocalizedString(@"aboutEwin", nil);
        _titleArray = @[@[changeOrganization,networkDataUse,updateData,function,errorDiagnosis,newMessage],@[aboutEwin]];
    }
    return _titleArray;
}


#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.titleArray count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.titleArray[section] count];
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
    static NSString* identifier = @"YWSettingsViewControllerCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.textLabel.font = KTitleFont;
        cell.detailTextLabel.font = KSmallContentFont;
    }
    cell.textLabel.text = self.titleArray[indexPath.section][indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.accessoryView = nil;
    cell.detailTextLabel.text = nil;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.detailTextLabel.text = currentUser.simpleName?:@"";
        }else if (indexPath.row == 1) {
            cell.accessoryView = self.netWorkSwitch;
        }else if (indexPath.row == 2){
            NSString *lastRefreshTime = [[NSUserDefaults standardUserDefaults] stringForKey:KLastRefreshJsonDataUserDefaultsKey];
            NSString *lastUpdateTime = NSLocalizedString(@"lastUpdateTime", nil);
            cell.detailTextLabel.text = lastRefreshTime.length ? [NSString stringWithFormat:@"%@:%@",lastUpdateTime,lastRefreshTime] : @"";
        }else{
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

#pragma mark - UITableViewDataDelegate mothods
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //切换机构
            [self surePreLoginOrganization];
        }else if (indexPath.row == 2) {
            [self reLoadJsonDatas];
        }else if (indexPath.row == 3){
            YWFunctionSettingTableViewController* functionVC = [[YWFunctionSettingTableViewController alloc] init];
            [self.navigationController pushViewController:functionVC animated:YES];
        }else if (indexPath.row == 4){
            YWErrorRecordFunctionViewController * errorRecordVC = [[YWErrorRecordFunctionViewController alloc] init];
            [self.navigationController pushViewController:errorRecordVC animated:YES];
        }else if (indexPath.row == 5){
            YWNewMessageSettingViewController* nmsvc = [[YWNewMessageSettingViewController alloc] init];
            [self.navigationController pushViewController:nmsvc animated:YES];
        }
    }else{
        YWAboutEwinViewController *aboutEwinVC = [[YWAboutEwinViewController alloc] init];
        [self.navigationController pushViewController:aboutEwinVC animated:YES];
    }
}

- (void)surePreLoginOrganization{
    [DJWActionSheet showInView:self.navigationController.view
                     withTitle:NSLocalizedString(@"makeSureChangeOrganization", nil)
             cancelButtonTitle:NSLocalizedString(@"cancel", nil)
        destructiveButtonTitle:NSLocalizedString(@"sure", nil)
             otherButtonTitles:nil
                      tapBlock:^(DJWActionSheet* actionSheet, NSInteger tappedButtonIndex) {
                          if (tappedButtonIndex == actionSheet.destructiveButtonIndex) {
                              [self handleWithChangeOrganizationEvent];
                          }
                      }];
}

- (void)handleWithChangeOrganizationEvent{
    //切换机构时检查是否有离线的任务
    BOOL isExist = [[YWWorkReminderManager shareManager] existUploadFailedMissions];
    if (isExist) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"pleaseNotice", nil) message:NSLocalizedString(@"hasUploadFailedRecordsWhenChangeOrganization", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self preLoginRequest];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self preLoginRequest];
    }
}

- (void)preLoginRequest{
    self.HUD.labelText = NSLocalizedString(@"loading", nil);
    [self.HUD show:YES];
    [[WMHttpTool shareHttpTool] cancelAllRequest];

    YWLoginUser* loginUser = [YWLoginTool loginUser];
    NSString *userAccount = loginUser.userAccount;
    NSString *passWord = loginUser.userPwd;
    
    [YWLoginTool preLoginRequestWithUserName:userAccount passWord:passWord isLogin:NO completeBlock:^(NSArray* organizations) {
        if (organizations.count == 1) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"hasNoOrganizationToChange", nil)];
        }else if (organizations.count > 1) {
            [self.HUD hide:YES];
            self.popupOrganizationViewController.organizations = organizations;
            [self presentPopupViewController:self.popupOrganizationViewController animationType:MJPopupViewAnimationSlideBottomBottom];
        }else{
            [self.HUD hide:YES];
        }
    }];
}

#pragma mark - YWPopupSelectOrganizationDelegate
- (void)selectedOrganization:(YWOrganization*)organization{
    self.HUD.labelText = NSLocalizedString(@"loadingDoMyBest", nil);
    [self.HUD show:YES];
    YWLoginUser* loginUser = [YWLoginTool loginUser];
    NSString *userAccount = loginUser.userAccount;
    NSString *passWord = loginUser.userPwd;
    
    [YWLoginTool loginRequestWithOrganizationNo:organization.organizationNo simpleName:organization.simpleName userName:userAccount passWord:passWord isLogin:NO completeBlock:^(NSInteger statusCode) {
        if (statusCode == 200) {
            //下载json数据
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[YWDownloadMetaDataManager shareManager] refreshJsonDatasWithComplete:^(BOOL error) {
                    [self.HUD hide:YES];
                    if (error) {
                        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"updateDataFailed", nil)];
                    }else{
                        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"updateDataSucceed", nil)];
                        currentUser = [YWLoginTool loginUser];
                        //各个模块的未读数和总数
                        [[YWEwinManager shareManager] selectIsExistNewMissionsUnReadCount];
                        //切换机构成功通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:KPushchangeOrganizationSuccess object:nil];
                        
                        //更新一下更新时间
                        NSString *currentTime = [YWCommonTool showTime:[[NSDate date] timeIntervalSince1970] andFormatter:KTimeFormatShortYearDateTime];
                        [[NSUserDefaults standardUserDefaults] setObject:currentTime forKey:KLastRefreshJsonDataUserDefaultsKey];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self.tableView reloadData];
                    }
                }];
            });
        }else{
            [self.HUD hide:YES];
        }
    }];
}

- (void)reLoadJsonDatas{
    //重新下载Json基础数据
    if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
        if ([[WMHttpTool shareHttpTool] networkType] == WMNetworkTypeWiFi) {
            [self refreshJsonDatas];
        }else{
            NSString *tip = NSLocalizedString(@"updateDataTips", nil);
            UIAlertController *alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tip preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self refreshJsonDatas];
            }]];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }else {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
    }
}

- (void)refreshJsonDatas{
    self.HUD.labelText = NSLocalizedString(@"updating", nil);
    [self.HUD show:YES];
    [[YWDownloadMetaDataManager shareManager] refreshJsonDatasWithComplete:^(BOOL error) {
        [self.HUD hide:YES];
        if (error) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"updateDataFailed", nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"updateDataSucceed", nil)];
            //更新一下更新时间
            NSString *currentTime = [YWCommonTool showTime:[[NSDate date] timeIntervalSince1970] andFormatter:KTimeFormatShortYearDateTime];
            [[NSUserDefaults standardUserDefaults] setObject:currentTime forKey:KLastRefreshJsonDataUserDefaultsKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.tableView reloadData];
        }
    }];
}

- (void)switchAction:(id)sender{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        YWLog(@"open");
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNetWorkType];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else {
        YWLog(@"close");
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:KNetWorkType];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (UITableView*)tableView{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        tableView.separatorColor = [UIColor customLineColor];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.sectionFooterHeight = 0.0f;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (UISwitch *)netWorkSwitch{
    if (!_netWorkSwitch) {
        UISwitch *netWorkSwitch = [[UISwitch alloc]init];
        BOOL kNetWorkType = [[[NSUserDefaults standardUserDefaults] objectForKey:KNetWorkType] boolValue];
        [netWorkSwitch setOn:kNetWorkType];
        [netWorkSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        _netWorkSwitch = netWorkSwitch;
    }
    return _netWorkSwitch;
}

- (YWPopupOrganizationViewController*)popupOrganizationViewController
{
    if (!_popupOrganizationViewController) {
        YWPopupOrganizationViewController* popupOrganizationViewController = [[YWPopupOrganizationViewController alloc] init];
        popupOrganizationViewController.parentVC = self;
        popupOrganizationViewController.delegate = self;
        _popupOrganizationViewController = popupOrganizationViewController;
    }
    return _popupOrganizationViewController;
}

@end
